import { message, Spin } from 'antd';
import React, { Fragment, useContext, useEffect, useState } from 'react'
import { reqSearchGra } from '@/api/api';
import { Context } from '@/App';
import { addGrade, deleteGrades, reqStuGrades, reqTeaGrades, updateGrade } from '@/api/api';
import useAdditionalInfor from '@/hooks/useAdditionalInfor';
import { searchColList, gradeTableColumn } from './tableColumns/index';
import './grade.less'

import AddGrade from '@/components/GradeUI/AddGrade';
import GradesList from '@/components/GradeUI/GradesList';
import GradesSearch from '@/components/GradeUI/GradesSearch'
import GradesUpload from '@/components/GradeUI/GradesUpload';
import UpdateGrade from '@/components/GradeUI/UpdateGrade';


export default function Grade() {
  const [openUpload, setOpenUpload] = useState(false);
  const [addOpen, setAddOpen] = useState(false);
  const [updateOpen, setUpdateOpen] = useState(false);
  const [loading, setLoading] = useState(true)

  const [grades, setGrades] = useState();
  const [searchInfor,setSearchInfor] = useState()
  const [updateInfor,setUpdateInfor] = useState()

  const { role } = useContext(Context)
  const {classes, curriculum } = useAdditionalInfor(role)

  useEffect(() => {
    if (role !== null) {
      defaulGrades(role)
    }
  }, [role])

  // 学生初始化
  const studentGrades = (values) => {
    setLoading(true)
    reqStuGrades(values).then(
      res => {
        if (res.status === 200) {
          setLoading(false)
          setGrades(res.data);
        }
        if (res.status === 201) {
          message.error("没有相应的成绩")
          setGrades(null)
        }
      },
      rej => { }
    )
  }

  // 教师初始化
  const teacherGrades = (values) =>{
    setLoading(true)
    setGrades(null)
    setLoading(false)
  }

  // 学生检索
  const studentSearch = (values) => {
    console.log(values);
    let data;
    if (Object.keys(values).every(key => values[key] === undefined)) {
      data = {
        fd_professional: role.fd_professional,
        fd_studNum: role.fd_idNum
      }
    } else {
      data = {
        fd_professional: role.fd_professional,
        fd_studNum: role.fd_idNum,
        ...values
      }
    }
    reqSearchGra(data).then(
      res => {
        if (res.status === 200) {
          setGrades(res.data)
        } else if (res.status === 201) {
          message.error("找不到相应课程考试信息")
          setGrades(null)
        }
      },
      rej => { }
    )
  };

  // 教师检索
  const teacherSearch = (values)=>{
    setSearchInfor(values)
    // setLoading(true)
    reqTeaGrades({...role,values}).then(
      res => {
        if (res.status === 200) {
          // setLoading(false)
          setGrades(res.data);
        }
        if (res.status === 201) {
          // setLoading(false)
          message.error("没有相应的成绩")
          setGrades(null)
        }
      },
    )
  }

  const defaulGrades = role?.fd_type === "student"? studentGrades :role?.fd_type ==="teacher"?teacherGrades:undefined

  const searchGrades = role?.fd_type === "student"? studentSearch :role?.fd_type ==="teacher"?teacherSearch:undefined

  // 重置数据
  const Reset = () => {
    defaulGrades(role)
  }

  // 上传文件
  const handleOk = () => {
    setOpenUpload(false);
  };

  // 删除操作
  const deleteGrade = (value) => {
    deleteGrades(value).then(
      res => {
        if(res.status === 200){
          message.success(res.data)
          teacherSearch(searchInfor)
        }
        if(res.status === 201){
          message.error("删除失败")
        }
      }
    )
  }

  // 添加成绩提交
  const addOnCreate = (values) => {
    const fd_comprehensiveScore = String((Number(values.fd_assessmentScore) + Number(values.fd_gradeInCourseWork) ) / 2)
    const fd_professional = role.fd_professional
    const addInfor= {fd_comprehensiveScore,fd_professional,...values}

    addGrade(addInfor).then(
      res =>{
        if(res.status === 200){
          message.success("添加成功")
          teacherSearch(searchInfor)
        }
      }
    )
    console.log(fd_comprehensiveScore);
    setAddOpen(false);
  };

  // 修改提交
  const updateOnCreate = (values) => {
    const fd_comprehensiveScore = String((Number(values.fd_assessmentScore) + Number(values.fd_gradeInCourseWork) ) / 2)
    const fd_professional = role.fd_professional
    const updateInfor= {fd_comprehensiveScore,fd_professional,...values}

    updateGrade(updateInfor).then(
      res =>{
        if(res.status === 200){
          message.success(res.data)
          teacherSearch(searchInfor)
        }
      },
    )

    setUpdateOpen(false);
  };


  // 修改成绩
  const cellHandleClick = (item) => {
    setUpdateInfor(item)
    setUpdateOpen(true);
  }

  const { studentColList, teacherColList } = searchColList({ classes, curriculum })
  const {studentColumn,teacherColumn} = gradeTableColumn(cellHandleClick,deleteGrade)
  
  // 表格头
  const column = role?.fd_type === "student"?studentColumn :role?.fd_type === "teacher"? teacherColumn:[]
  const style = role?.fd_type === "student"?"grades-select-stu" :role?.fd_type === "teacher"? 'grades-select-tea':''

  return (
    <Fragment>
      <div className='grades-box'>
        {
          loading ? <Spin size='large' className='loading' /> :
            <>
              <div className={style}>
                <GradesSearch
                  setOpenUpload={setOpenUpload}
                  setAddOpen={setAddOpen}
                  Reset={Reset}
                  onFinish={searchGrades}
                  role={role}
                  studentColList={studentColList}
                  teacherColList={teacherColList}
                />
              </div>
              <div className='grades-table'>
                <GradesList
                  column={column}
                  grades={grades}
                  role={role}
                 
                />
              </div>
            </>
        }
        {/* 上传文件 */}
        <GradesUpload
          open={openUpload}
          onOk={handleOk}
          onCancel={() => {
            setOpenUpload(false);
          }}
        />
        {/* 添加 */}
        <AddGrade
          open={addOpen}
          onCreate={addOnCreate}
          onCancel={() => {
            setAddOpen(false);
          }}
          role ={role}
          curriculum={curriculum}
        />
        {/* 修改成绩 */}
        <UpdateGrade
          updateInfor={updateInfor}
          open={updateOpen}
          role={role}
          curriculum={curriculum}
          onCreate={updateOnCreate}
          onCancel={() => {
            setUpdateOpen(false);
          }}
        />
      </div>
    </Fragment>
  )
}
